from fastapi import APIRouter, Request
from pyJianYingDraft import CapCut_Voice_filters_effect_type, CapCut_Voice_characters_effect_type, \
    CapCut_Speech_to_song_effect_type, Tone_effect_type, Audio_scene_effect_type, Speech_to_song_type
from .base import RouterMeta
from src.constants.resultcode import ResultCode
from src.utils.response import ApiResponse
from src.utils.logger import get_logger
import config
from src.schemas.audio import DraftAddAudioRequest
from src.service.add_audio import add_audio_track

logger = get_logger("capcut")
router = APIRouter()


@router.get("/effect_types",name="获取可用音频特效")
async def get_audio_effect_types(request: Request):
    """
    获取可用音频特效
    """
    try:
        audio_effect_types = []

        if config.IS_CAPCUT_ENV:
            # Return audio effect types in CapCut environment
            # 1. Voice filters effect types
            for name, member in CapCut_Voice_filters_effect_type.__members__.items():
                params_info = []
                for param in member.value.params:
                    params_info.append({
                        "name": param.name,
                        "default_value": param.default_value * 100,
                        "min_value": param.min_value * 100,
                        "max_value": param.max_value * 100
                    })

                audio_effect_types.append({
                    "name": name,
                    "type": "Voice_filters",
                    "params": params_info
                })

            # 2. Voice characters effect types
            for name, member in CapCut_Voice_characters_effect_type.__members__.items():
                params_info = []
                for param in member.value.params:
                    params_info.append({
                        "name": param.name,
                        "default_value": param.default_value * 100,
                        "min_value": param.min_value * 100,
                        "max_value": param.max_value * 100
                    })

                audio_effect_types.append({
                    "name": name,
                    "type": "Voice_characters",
                    "params": params_info
                })

            # 3. Speech to song effect types
            for name, member in CapCut_Speech_to_song_effect_type.__members__.items():
                params_info = []
                for param in member.value.params:
                    params_info.append({
                        "name": param.name,
                        "default_value": param.default_value * 100,
                        "min_value": param.min_value * 100,
                        "max_value": param.max_value * 100
                    })

                audio_effect_types.append({
                    "name": name,
                    "type": "Speech_to_song",
                    "params": params_info
                })
        else:
            # Return audio effect types in JianYing environment
            # 1. Tone effect types
            for name, member in Tone_effect_type.__members__.items():
                params_info = []
                for param in member.value.params:
                    params_info.append({
                        "name": param.name,
                        "default_value": param.default_value * 100,
                        "min_value": param.min_value * 100,
                        "max_value": param.max_value * 100
                    })

                audio_effect_types.append({
                    "name": name,
                    "type": "Tone",
                    "params": params_info
                })

            # 2. Audio scene effect types
            for name, member in Audio_scene_effect_type.__members__.items():
                params_info = []
                for param in member.value.params:
                    params_info.append({
                        "name": param.name,
                        "default_value": param.default_value * 100,
                        "min_value": param.min_value * 100,
                        "max_value": param.max_value * 100
                    })

                audio_effect_types.append({
                    "name": name,
                    "type": "Audio_scene",
                    "params": params_info
                })

            # 3. Speech to song effect types
            for name, member in Speech_to_song_type.__members__.items():
                params_info = []
                for param in member.value.params:
                    params_info.append({
                        "name": param.name,
                        "default_value": param.default_value * 100,
                        "min_value": param.min_value * 100,
                        "max_value": param.max_value * 100
                    })

                audio_effect_types.append({
                    "name": name,
                    "type": "Speech_to_song",
                    "params": params_info
                })

        return ApiResponse.success(
            data=audio_effect_types,
        )

    except Exception as e:
        logger.error(f"获取可用音频特效失败: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"获取可用音频特效失败: {str(e)}",
        )

@router.post("/add_audio",name="添加音频")
async def add_audio(request: Request, audio_request: DraftAddAudioRequest):


    # # If there are audio effect parameters, combine them into sound_effects format
    sound_effects = None
    if audio_request.effect_type is not None:
        sound_effects = [(audio_request.effect_type, audio_request.effect_params)]

    try:
        # Call the modified add_audio_track method
        draft_result = add_audio_track(
            draft_folder=audio_request.draft_folder,
            audio_url=audio_request.audio_url,
            start=audio_request.start,
            end=audio_request.end,
            target_start=audio_request.target_start,
            draft_id=audio_request.draft_id,
            volume=audio_request.volume,
            track_name=audio_request.track_name,
            speed=audio_request.speed,
            sound_effects=sound_effects,  # Add audio effect parameters
            width=audio_request.width,
            height=audio_request.height,
            duration=audio_request.duration  # Add duration parameter
        )

        return ApiResponse.success(
            data=draft_result
        )


    except Exception as e:
        logger.error(f"添加音频失败: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"添加音频失败失败: {str(e)}",
        )



# 路由元数据配置
meta = RouterMeta(
    router=router,
    prefix="/audio",
    tags=["音频"]
)